package rmhc.api.fb
{
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import rmhc.api.ApiWrapper;
	import rmhc.gui.SupplyFunctions;
	
	public class GetIdsThumbs extends FbApiTask
	{
		protected var pics:Dictionary;
		protected var cids:Array;
		
		protected var gp:FbApiTask;
		
		public function GetIdsThumbs(wrapper:ApiWrapper, ids:Array )
		{
			//var p:Object = { "ids" : ids.join( "," ) , "fields" : "id,from,images" };
			var p:Object = { "ids" : ids.join( "," ) , "fields" : "id,from,type,cover_photo" , offset : 0 , limit : 10000 };
			super(wrapper, "albums" , p );
		}
		
		override public function parseData(result:Object, fail:Object=null):void
		{
			cids = new Array();
			for each ( var us:Object in result )
			{
				for each ( var alb:Object in us.data )
				{
					//trace( "album" , SupplyFunctions.objectToString( alb ) );
					if ( alb.type == "profile" )
					{
						if ( alb.cover_photo && alb.cover_photo.length > 0 )
						{
							//trace( "pic id: " + alb.cover_photo + "*" );
							cids.push( alb.cover_photo );
						}
					}
				}
			}
			var p:Object = { ids : cids.join( "," ) , offset : 0 , limit : 10000 /*, fields : "id,from,images"*/ };
			gp = new FbApiTask( wrapper , null , p );
			gp.addEventListener( Event.COMPLETE , onGetPics );
			gp.run();
		}
		protected function onGetPics( e:Event ):void
		{
			var raw:Object = gp.getRawData();
			pics = new Dictionary();
			for each ( var pic:Object in raw )
			{
				var thumb:Object = getSmallestPic( pic.images );
				pics[String( pic.from.id )] = thumb.source;
				trace( "pic" , pic.id , thumb.source );
			}
			onComplete();
		}
		protected function getSmallestPic( images:Array ):Object
		{
			var res:Object;
			for each ( var i:Object in images )
			{
				if ( res == null || ( i.width < res.width && i.width > 100 ) )
				{
					res = i;
				}
			}
			
			return res;
		}
		
		public function getThumbSrc( id:String ):String
		{
			return pics[id];
		}
	}
}